package model

import (
	"time"

	"gitee.com/goframe/lt-collector/libs/orma"
)

type (
	GameSysTmp struct {
		orma.BaseModel `xorm:"extends"`

		Gid      int64  `json:"gid" xorm:"notnull index"`
		OpenCode string `json:"open_code" xorm:"varchar(200) notnull"`
	}
)

func (m *GameSysTmp) GetOpenIssue() string {
	return ""
}

func (m *GameSysTmp) GetOpenCode() string {
	return m.OpenCode
}

func (m *GameSysTmp) GetOpenTime() orma.JSONTime {
	return orma.JSONTime(time.Now())
}

func (m *GameSysTmp) Count() int64 {
	count, _ := m.Session().Count(m)
	return count
}

func (m *GameSysTmp) Append(codes []string) (code string, err error) {
	has, e := m.Session().Asc("id").Limit(1).Get(m)
	if e != nil {
		err = e
		return
	}
	if has {
		code = m.OpenCode
		_, _ = m.Session().ID(m.ID).Unscoped().NoAutoCondition().Delete(m)
	} else {
		code = codes[0]
		codes = codes[1:]
	}
	if len(codes) == 0 {
		return
	}
	beans := make([]*GameSysTmp, 0, len(codes))
	for _, code := range codes {
		beans = append(beans, &GameSysTmp{
			Gid:      m.Gid,
			OpenCode: code,
		})
	}
	if _, err = m.Session().Insert(beans); err != nil {
		return
	}
	return
}
